package com.msite.config;

import com.msite.service.security.CustomUserDetailsService;
import com.msite.service.security.SimpleLoginSuccessHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.PriorityOrdered;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.header.writers.frameoptions.XFrameOptionsHeaderWriter;

/**
 * Created by tpeng on 2016/4/19.
 */
@Configuration
@EnableWebSecurity
@Order(PriorityOrdered.HIGHEST_PRECEDENCE)
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private CustomUserDetailsService customUserDetailsService;

  /*@Bean
    public AuthenticationProvider authenticationProvider() {
        return new BasicAuthenticationProvider();
    }*/

    @Override
    protected void configure(AuthenticationManagerBuilder builder) throws Exception {

        builder.userDetailsService(customUserDetailsService)
                .passwordEncoder(passwordEncoder());//code5 //不删除凭据，以便记住用户   
                builder.eraseCredentials(false);

        /*builder.inMemoryAuthentication()
                .withUser("user").password("user").roles("USER")
                .and().withUser("admin").password("admin").roles("ADMIN");*/
    }

    @Bean
    public BCryptPasswordEncoder passwordEncoder(){ return new BCryptPasswordEncoder(4); }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.sessionManagement()
                .invalidSessionUrl("/timeout_");
               // .maximumSessions(1); //同一用户只能一个登录 需要配org.springframework.security.web.session.HttpSessionEventPublisher监听
        http.csrf().disable()
                .authorizeRequests()
                .antMatchers("/js/**", "/images/**")
                .permitAll()
                .anyRequest().authenticated()
                .and()
                .formLogin()
                    .usernameParameter("username")
                    .passwordParameter("password")
                    .loginProcessingUrl("/j_login")
                    .loginPage("/login_")
                    //.defaultSuccessUrl("/index_", true)
                .failureUrl("/login_")
                .successHandler(loginSuccessHandler("/index_", true))
                    .permitAll()
                .and()
                .logout()
                    .logoutSuccessUrl("/login_")
                    .logoutUrl("/logout")
                    .permitAll()
                    .deleteCookies("JSESSIONID")
                    .invalidateHttpSession(true)
                .and()
                    .rememberMe()
                    .tokenValiditySeconds(604800)
                    .useSecureCookie(true)
                .and()
                .headers()
                .addHeaderWriter(new XFrameOptionsHeaderWriter(XFrameOptionsHeaderWriter.XFrameOptionsMode.SAMEORIGIN));
    }

    @Bean
    public SimpleLoginSuccessHandler loginSuccessHandler(final String defaultTargetUrl, final boolean isAlwaysUse){
        return new SimpleLoginSuccessHandler(defaultTargetUrl, isAlwaysUse);
    }
}
